package models;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;

import play.db.ebean.Model;

import com.avaje.ebean.ExpressionList;
import com.avaje.ebean.Page;

/*
 * Product model
 * Author: Talasbek Assem
 */

@Entity
public class Product extends Model {

	@Id
	public Long id;
	
	public String title;
	public Double price;
	public Integer quantity;
	
	public String description;
	
	public String producer;
	
	@Column(nullable = true)
	@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.REFRESH})
	public Category category;

	@Column(nullable = true)
	@OneToMany(cascade = CascadeType.ALL)
	public List<Image> imageList;
	
	public static Finder<Long, Product> find = new Finder<Long, Product>(Long.class, Product.class);
	
	public static Product create(String title, Double price, Integer quantity, Category category)
	{
		Product product = new Product();
		product.title = title;
		product.price = price;
		product.quantity = quantity;
		product.category = category;
		return product;
	}
	
	public static Page<Product> page(int page, int pageSize, String producer, String priceStart, String priceEnd, String sortBy, String order, String filter)
	{
		ExpressionList<Product> list = find.where().ilike("title", "%"+filter+"%");
		
		if(!producer.equals(""))
			list = list.where().eq("producer", producer);
		if(!priceStart.equals("0") && !priceEnd.equals("0"))
			list = list.where().between("price", priceStart, priceEnd);
		
		return list.orderBy(sortBy + " " + order)
				.findPagingList(pageSize)
				.getPage(page);
	}
}